<?php
namespace app\Services\admin;

use yii;
use app\commands\LibUtil;
use app\models\User;
use app\models\Ivtcode;
use Lcobucci\JWT\Signer\Hmac\Sha256;
use Lcobucci\JWT\Builder;
use Lcobucci\JWT\Signer\Key;
use yii\data\Pagination;
use app\Services\ApiService;
use app\models\Country;

class UserService extends ApiService
{
    /**
     * @return Service_Pay
     */
    public static function getInstance()
    {
        return parent::getInstance();
    }

    /**
     * 用户列表 (默认普通用户) 1=普通用户 2=记者  3=VIP
     */
    public function getUserList($req){
        $limit = !empty($req['num'])?$req['num']:10;
        $offset = !empty($req['page'])?($req['page']-1)*$limit:0;
        $where = ['Level'=>1];
        if (!empty($req['Level'])){
            $where['Level'] = $req['Level'];
        }
        # 姓名 公司 手机号 邮箱 帐号
        if (!empty($req['name'])){
            $where['Name'] = $req['name'];
        }
        if (!empty($req['Company'])){
            $where['Company'] = $req['Company'];
        }
        if (!empty($req['Cellphone'])){
            $where['Cellphone'] = $req['Cellphone'];
        }
        if (!empty($req['email'])){
            $where['email'] = $req['email'];
        }
        $model = User::find()
            ->select('ID,Name,Username,IDcard,Cellphone,CountryID,Company,email,Position,Activity,Nickname,Password,EnglishName,EnglishCompany,EnglishPosition')
            ->where($where);

        if (!empty($req['keywords'])){
            $keywords = $req['keywords'];
            $model = $model->where(['like', 'name', $keywords])
                        ->orWhere(['like','Company',$keywords])
                        ->orWhere(['like','Cellphone',$keywords])
                        ->orWhere(['like','Username',$keywords])
                        ->orWhere(['like','email',$keywords]);
        }
        $totalCount  = $model->count();
        if (!$totalCount){
            return ['code'=>200,'message'=>'暂无数据'];
        }
        $pages = new Pagination(['totalCount' => $model->count()]);
        //  ->orderBy('ID DESC')
        $list = $model->offset($offset)
            ->limit($limit)
            ->asArray()
            ->all();
        if (empty($list)){
            return ['code'=>200,'message'=>'暂无数据'];
        }
        foreach ($list AS &$user){
            $country = Country::find()
                ->select('name')
                ->where(['ID'=>$user['CountryID']])
                ->asArray()
                ->one();
            $user['CountryName'] = $country['name'];
        }
        return ['code'=>200,'data'=>['list'=>$list,'totalCount'=>intval($totalCount)]];
    }


    /**
     * 用户详情
     */
    public function getUserInfo($userID){
        $info = User::find()
            ->select('ID, Username,  Company,  Position,  Cellphone,  Name,  IDcard,  CountryID,email,  Activity,  Regist,  Level, Password')
            ->where(['ID'=>$userID])
            ->asArray()
            ->one();
        if (empty($info)){
            return ['code'=>200,'message'=>'暂无数据'] ;
        }
        # 用户的地区/国籍信息
        $country = Country::find()
            ->select('name')
            ->where(['ID'=>$info['CountryID']])
            ->asArray()
            ->one();
        $info['CountryName'] = $country['name'];
        unset($info['CountryID']);
        return ['code'=>200,'data'=>$info] ;
    }


    /**
     * 保存用户信息
     */
    public function saveUserInfo($req){
        if (empty($req['Cellphone']) && empty($req['email'])){
            return ['code'=>-1,'message'=>'手机号和邮箱必须填1个','data'=>[]] ;
        }
        if (!empty($req['Cellphone']) && !empty($req['email'])){
            return ['code'=>-1,'message'=>'手机号和邮箱只需要写一个','data'=>[]] ;
        }

        if (empty($req['userID'])){
            # 昵称唯一
            $is_exit = User::find()
                ->where(['Nickname'=>$req['Nickname']])
                ->count();
            if ($is_exit){
                return ['code'=>-1,'message'=>'昵称重复，请修改','data'=>[]] ;
            }
        }

        # 手机号唯一
        if (!empty($req['Cellphone'])&&empty($req['userID'])){
            $is_exit = User::find()
                ->where(['Cellphone'=>$req['Cellphone']])
                ->count();
            if ($is_exit){
                return ['code'=>-1,'message'=>'手机号重复，请修改','data'=>[]] ;
            }
            $user_name = $req['Cellphone'];
        }
        #邮箱唯一
        if (!empty($req['email'])&&empty($req['userID'])){
            $is_exit = User::find()
                ->where(['email'=>$req['email']])
                ->count();
            if ($is_exit){
                return ['code'=>-1,'message'=>'邮箱重复，请修改','data'=>[]] ;
            }
        }
        if (!empty($req['Cellphone'])){
            $user_name = $req['Cellphone'];
        }
        if (!empty($req['email'])){
            $user_name = $req['email'];
        }
        $time = date("Y-m-d H:i:s",time());
        $info = [
            'Username' => $user_name,
            'Name'     => $req['Name'],
            'Nickname' => !empty($req['Nickname'])?$req['Nickname']:'',
            'Company'  => !empty($req['Company'])?$req['Company']:'',
            'Position' => !empty($req['Position'])?$req['Position']:'',
            'EnglishName'       => !empty($req['EnglishName'])?$req['EnglishName']:null,
            'EnglishCompany'    => !empty($req['EnglishCompany'])?$req['EnglishCompany']:null,
            'EnglishPosition'   => !empty($req['EnglishPosition'])?$req['EnglishPosition']:null,
            'Cellphone'=> !empty($req['Cellphone'])?$req['Cellphone']:null,
            'email'    => !empty($req['email'])?$req['email']:null,
            'IDcard'   => !empty($req['IDcard'])?$req['IDcard']:null,
            'CountryID'=> !empty($req['CountryID'])?$req['CountryID']:null,
            'Activity' => !empty($req['Activity'])?$req['Activity']:1,
            'Level'    => !empty($req['Level'])?$req['Level']:1,
            'updatetime' => $time,
        ];
        if (!empty($req['userID'])){
            $count = User::find()
                ->where(['ID'=>$req['userID']])
                ->count();
            if (!$count){
                return ['code'=>-1,'message'=>'没有该用户','data'=>[]] ;
            }
            # update
            $res = Yii::$app->db->createCommand()->update('`user.user`',$info , ['ID'=>$req['userID']])->execute();
        }else{
            $info['Regist'] = $time;
            $res = Yii::$app->db->createCommand()->insert('`user.user`',$info )->execute();
            if ($res){
                // 用户名片  模型  隐私
                $userID = Yii::$app->db->getLastInsertId();
                $card = ['style'=>1,'Activity'=>1,'userID'=>$userID];
                Yii::$app->db->createCommand()->insert('`pltf.card`',$card )->execute();
                $avter = ['userID'=>$userID,'modID'=>1];
                Yii::$app->db->createCommand()->insert('`user.avter`',$avter )->execute();
                $limit = ['message'=>1,'card'=>1,'userID'=>$userID];
                Yii::$app->db->createCommand()->insert('`user.limit`',$limit )->execute();
            }
        }
        if ($res){
            return ['code'=>200,'message'=>'保存成功'];
        }
        return ['code'=>-1,'message'=>'保存失败，请稍后重试'];
    }


    /**
     *  解封/封禁用户
     *
     */
    public function activeUser($req){
        $info = User::find()
            ->where(['ID'=>$req['userID']])
            ->count();
        if (empty($info)){
            return ['code'=>-1,'message'=>'没有该用户'] ;
        }
        $update = [
            'updatetime' => date("Y-m-d H:i:s",time()),
            'Activity'   => intval($req['Activity'])
        ];
        $res = Yii::$app->db->createCommand()->update('`user.user`' ,$update, ['ID'=> intval($req['userID'])])->execute();
        if ($res){
            return ['code'=>200,'message'=>'操作成功'];
        }
        return ['code'=>-1,'message'=>'操作失败，请稍后重试'];
    }

    /**
     * 获取全部用户数据
     */
    public function getAllList($req){
        $limit = !empty($req['num'])?$req['num']:10;
        $offset = !empty($req['page'])?($req['page']-1)*$limit:0;

        $model = User::find()
            ->select('ID,Name,Username,IDcard,Cellphone,CountryID,Company,email,Position,Activity,Nickname,Password');
        $totalCount  = $model->count();
        if (!$totalCount){
            return ['code'=>200,'message'=>'暂无数据'];
        }
        $pages = new Pagination(['totalCount' => $model->count()]);
        $list = $model->offset($offset)
            ->limit($limit)
            ->asArray()
            ->all();

        $list = $model->offset($offset)
            ->limit($limit)
            ->asArray()
            ->all();
        if (empty($list)){
            return ['code'=>200,'message'=>'暂无数据'];
        }
        foreach ($list AS &$user){
            $country = Country::find()
                ->select('name')
                ->where(['ID'=>$user['CountryID']])
                ->asArray()
                ->one();
            $user['CountryName'] = $country['name'];
        }
        return ['code'=>200,'data'=>['list'=>$list,'totalCount'=>intval($totalCount)]];
    }

}